﻿using System;
using System.Collections.Generic;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Electrical;
using Autodesk.Revit.UI;
using YArchitech.Revit.Electric.Common;

namespace YArchitech.MEP.Electric.CableLay
{
	public class CableTrayDim
	{
		public CableTrayDim(UIDocument uiDoc)
		{
			this.m_uiDoc = uiDoc;
			this.m_doc = uiDoc.ActiveView.Document;
		}

		public void DoDim()
		{
			CableTrayDimForm cableTrayDimForm = new CableTrayDimForm();
			cableTrayDimForm.Show(WindowHelper.HWndRevit);
			WindowHelper.SendMessageToWndRevit();
			Transaction transaction = null;
			Guid guid = new Guid("A24A6667-A400-4A48-93AA-41805D836C3D");
			try
			{
				for (;;)
				{
					Reference reference = this.m_uiDoc.Selection.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element, new CableTrayFilter(), "请选择要标注的桥架");
					Element element = this.m_doc.GetElement(reference);
					if (element != null)
					{
						CableTray cableTray = element as CableTray;
						List<CableTraySchemaData> list = new List<CableTraySchemaData>();
						if (!CableTraySchemaDataManager.GetData(cableTray, ref list))
						{
							TaskDialog.Show("盈建科提示", "从选择的桥架里未获取到敷设的电缆数据。");
						}
						else
						{
							List<string> list2 = new List<string>();
							foreach (CableTraySchemaData cableTraySchemaData in list)
							{
								list2.Add(cableTraySchemaData.CableNumber);
							}
							if (list2.Count <= 0)
							{
								TaskDialog.Show("盈建科提示", "未获取到桥架里敷设的电缆数据。");
							}
							else
							{
								XYZ globalPoint = reference.GlobalPoint;
								IntersectionResult intersectionResult = ((cableTray.Location as LocationCurve).Curve as Line).Project(globalPoint);
								XYZ ptS = new XYZ(intersectionResult.XYZPoint.X, intersectionResult.XYZPoint.Y, globalPoint.Z);
								transaction = new Transaction(this.m_doc, "CableTrayDim");
								transaction.Start();
								ElementId dimData = CableTraySchemaDim.GetDimData(element, guid);
								if (dimData != null && dimData != ElementId.InvalidElementId)
								{
									this.m_doc.Delete(dimData);
								}
								XYZ ptDim = this.m_uiDoc.Selection.PickPoint("请拾取标注点:");
								LeadStyle leadStyle = cableTrayDimForm.LeadStyle;
								LeadSymbol leadSymbol = cableTrayDimForm.LeadSymbol;
								Group group = ElectricalDimUtil.CreateCableTrayDim(this.m_doc, ptS, ptDim, leadStyle, leadSymbol, list2);
								CableTraySchemaDim.SetDimData(element, guid, "CableNumberSet", group.Id);
								transaction.Commit();
							}
						}
					}
				}
			}
			catch (Exception)
			{
				if (transaction != null && (int)transaction.GetStatus() != 3)
				{
					transaction.RollBack();
				}
			}
			finally
			{
				cableTrayDimForm.Close();
			}
		}

		private UIDocument m_uiDoc;

		private Document m_doc;
	}
}
